<script setup lang="ts">
import { computed, ref } from 'vue';

import { useVbenDrawer } from '@vben/common-ui';
import { $t } from '@vben/locales';
import { cloneDeep, getPopupContainer } from '@vben/utils';

import { useVbenForm } from '#/adapter/form';
import { configInfo, configAdd, configUpdate } from '#/api/rule/config';
import { defaultFormValueGetter, useBeforeCloseDiff } from '#/utils/popup';

import { drawerSchema } from './data';
import { allProjects } from '#/api/clinical/project';
import { trialListByProject } from '#/api/clinical/trial';

const emit = defineEmits<{ reload: [] }>();

const isUpdate = ref(false);
const title = computed(() => {
  return isUpdate.value ? $t('pages.common.edit') : $t('pages.common.add');
});

const [BasicForm, formApi] = useVbenForm({
  commonConfig: {
    // 默认占满两列
    formItemClass: 'col-span-2',
    // 默认label宽度 px
    labelWidth: 80,
    // 通用配置项 会影响到所有表单项
    componentProps: {
      class: 'w-full',
    },
  },
  schema: drawerSchema(),
  showDefaultActions: false,
  wrapperClass: 'grid-cols-2',
});

const { onBeforeClose, markInitialized, resetInitialized } = useBeforeCloseDiff(
  {
    initializedGetter: defaultFormValueGetter(formApi),
    currentGetter: defaultFormValueGetter(formApi),
  },
);

const [BasicDrawer, drawerApi] = useVbenDrawer({
  // 在这里更改宽度
  class: 'w-[550px]',
  onBeforeClose,
  onClosed: handleClosed,
  onConfirm: handleConfirm,
  onOpenChange: async (isOpen) => {
    if (!isOpen) {
      return null;
    }
    drawerApi.drawerLoading(true);
    Promise.all([getProjects()]);
    const { id } = drawerApi.getData() as { id?: number | string };
    isUpdate.value = !!id;

    if (isUpdate.value && id) {
      const record = await configInfo(id);
      // 关键：先根据回显的项目ID，手动加载对应的试验列表
      if (record.projectId) {
        await getTrialsByProjectId(record.projectId);
      }
      await formApi.setValues(record);
    }
    await markInitialized();

    drawerApi.drawerLoading(false);
  },
});
// 所属项目
const getProjects = () => {
  formApi.updateSchema([
    {
      fieldName: 'projectId',
      componentProps: (formModel) => ({
        getPopupContainer,
        api: () => allProjects(),
        fieldNames: {
          label: 'name',
          value: 'id',
        },
        onChange: (value: string) => {
          // 项目变化时，清空试验字段并重新加载试验列表
          formModel.clinicalTrialId = undefined;
          formApi.updateSchema([
            {
              componentProps: { options: [] },
              fieldName: 'clinicalTrialId',
            },
          ]);
          getTrialsByProjectId(value);
        },
      }),
    },
  ]);
};
// 项目下的实验
const getTrialsByProjectId = async (projectId: string | number) => {
  const trials = await trialListByProject(projectId);
  formApi.updateSchema([
    {
      fieldName: 'clinicalTrialId',
      componentProps: {
        getPopupContainer,
        options: trials,
        fieldNames: {
          label: 'name',
          value: 'id',
        },
      },
    },
  ]);
};

async function handleConfirm() {
  try {
    drawerApi.lock(true);
    const { valid } = await formApi.validate();
    if (!valid) {
      return;
    }
    // getValues获取为一个readonly的对象 需要修改必须先深拷贝一次
    const data = cloneDeep(await formApi.getValues());
    await (isUpdate.value ? configUpdate(data) : configAdd(data));
    resetInitialized();
    emit('reload');
    drawerApi.close();
  } catch (error) {
    console.error(error);
  } finally {
    drawerApi.lock(false);
  }
}

async function handleClosed() {
  await formApi.resetForm();
  resetInitialized();
}
</script>

<template>
  <BasicDrawer :title="title">
    <BasicForm />
  </BasicDrawer>
</template>
